#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
脑电设备控制器 - FastAPI版本
支持多用户会话管理和异步处理
"""

import sys
import os
import asyncio
import time
import uuid
import logging
from typing import Dict, Optional, Any
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

from fastapi import FastAPI, HTTPException, BackgroundTasks, WebSocket, WebSocketDisconnect
from fastapi.responses import JSONResponse
import uvicorn

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
sys.path.insert(0, project_root)

from models.brain_state_models import BrainStateOutput, DeviceConnectionRequest, AnalysisParams
from service.WaveService import WaveService
from service.BrainStateService import BrainStateService
from service.ProgressiveDataManager import ProgressiveDataManager
from response.BrainWaveResult import BrainWaveResult
from exception.base_exceptions import DeviceConnectionException, APIException
from exception.exception_handler import global_exception_handler

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# FastAPI应用实例
app = FastAPI(title="脑电设备控制API", version="1.0.0")

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 全局会话管理器
class SessionManager:
    """多用户会话管理器"""
    
    def __init__(self):
        self.sessions: Dict[str, Dict[str, Any]] = {}
        self.websocket_connections: Dict[str, WebSocket] = {}
        self.executor = ThreadPoolExecutor(max_workers=10)
        
    def create_session(self, session_id: str = None, room_id: str = None) -> str:
        """创建新会话"""
        if not session_id:
            session_id = str(uuid.uuid4())
        
        # 如果没有提供 room_id，使用环境变量默认值
        if not room_id:
            room_id = os.getenv('DEFAULT_ROOM_ID', 'default_room')
        if room_id == "None":
            room_id = None
        
        self.sessions[session_id] = {
            'id': session_id,
            'created_at': datetime.now(),
            'is_connected': False,
            'is_recording': False,
            'wave_service': None,
            'brain_state_service': None,
            'analysis_params': AnalysisParams(),
            'device_port': None,
            'room_id': room_id,  # 添加房间ID
            'last_result': None,
            'data_buffer': [],  # 数据缓冲区（保留兼容性）
            'last_analysis_time': None,  # 上次分析时间
            'progressive_manager': ProgressiveDataManager(session_id)  # 渐进式数据管理器
        }
        
        logger.info(f"创建会话: {session_id}, 房间ID: {room_id}")
        return session_id
    
    def get_session(self, session_id: str) -> Optional[Dict[str, Any]]:
        """获取会话信息"""
        return self.sessions.get(session_id)
    
    def remove_session(self, session_id: str):
        """移除会话"""
        if session_id in self.sessions:
            session = self.sessions[session_id]
            # 清理资源
            if session['wave_service']:
                try:
                    session['wave_service'].disconnect_device()
                except:
                    pass
            
            # 重置渐进式数据管理器
            if 'progressive_manager' in session:
                session['progressive_manager'].reset()
            
            # 关闭WebSocket连接
            if session_id in self.websocket_connections:
                del self.websocket_connections[session_id]
            
            # 关闭渐进式WebSocket连接
            progressive_key = f"{session_id}_progressive"
            if progressive_key in self.websocket_connections:
                del self.websocket_connections[progressive_key]
            
            del self.sessions[session_id]
            logger.info(f"移除会话: {session_id}")

# 全局会话管理器实例
session_manager = SessionManager()
# 连接脑电设备
@app.post("/api/device/connect")
async def connect_device(request: DeviceConnectionRequest, session_id: str = None):
    """
    连接脑电设备
    
    Args:
        request: 连接请求参数
        session_id: 会话ID（可选，不提供则自动创建）
    
    Returns:
        连接结果
    """
    try:
        # 创建或获取会话
        if not session_id:
            session_id = session_manager.create_session(room_id=request.room_id)
        elif not session_manager.get_session(session_id):
            session_id = session_manager.create_session(session_id, room_id=request.room_id)
        
        session = session_manager.get_session(session_id)
        
        # 检查是否已连接
        if session['is_connected']:
            return JSONResponse({
                "success": False,
                "message": "设备已连接",
                "session_id": session_id
            })
        
        # 异步连接设备
        def connect_device_sync():
            try:
                wave_service = WaveService(
                    port=request.port,
                    enable_notch_filter=True,
                    enable_eog_removal=False,
                    use_delta_service=True,
                    enable_theta_optimization=True,
                    enable_advanced_filter=True,
                    enable_band_optimization=True
                )
                
                if wave_service.connect_device():
                    session['wave_service'] = wave_service
                    session['brain_state_service'] = BrainStateService(use_8_bands=True)
                    session['is_connected'] = True
                    session['device_port'] = request.port
                    return True
                return False
            except Exception as e:
                connection_error = DeviceConnectionException(
                    f"设备连接失败: {e}"
                )
                global_exception_handler.handle_exception(connection_error)
                return False
        
        # 在线程池中执行连接
        loop = asyncio.get_event_loop()
        success = await loop.run_in_executor(session_manager.executor, connect_device_sync)
        
        if success:
            return JSONResponse({
                "success": True,
                "message": "设备连接成功",
                "session_id": session_id,
                "device_port": request.port,
                "room_id": session['room_id']
            })
        else:
            return JSONResponse({
                "success": False,
                "message": "设备连接失败",
                "session_id": session_id
            }, status_code=400)
            
    except Exception as e:
        api_error = APIException(
            f"连接设备API异常: {e}",
            endpoint="connect_device"
        )
        global_exception_handler.handle_exception(api_error)
        raise HTTPException(status_code=500, detail=f"连接设备失败: {str(e)}")
# 断开设备连接
@app.post("/api/device/disconnect/{session_id}")
async def disconnect_device(session_id: str):
    """
    断开设备连接
    
    Args:
        session_id: 会话ID
    
    Returns:
        断开结果
    """
    try:
        session = session_manager.get_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话不存在")
        
        if not session['is_connected']:
            return JSONResponse({
                "success": False,
                "message": "设备未连接",
                "session_id": session_id
            })
        
        # 停止记录
        session['is_recording'] = False
        
        # 断开设备
        if session['wave_service']:
            session['wave_service'].disconnect_device()
            session['wave_service'] = None
        
        session['brain_state_service'] = None
        session['is_connected'] = False
        session['device_port'] = None
        
        return JSONResponse({
            "success": True,
            "message": "设备已断开",
            "session_id": session_id
        })
        
    except Exception as e:
        exception = APIException(f"断开设备异常: {str(e)}")
        global_exception_handler.handle_exception(exception)
        raise HTTPException(status_code=500, detail=f"断开设备失败: {str(e)}")
# 获取设备状态
@app.get("/api/device/status/{session_id}")
async def get_device_status(session_id: str):
    """
    获取设备状态
    
    Args:
        session_id: 会话ID
    
    Returns:
        设备状态信息
    """
    try:
        session = session_manager.get_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话不存在")
        
        # 检查信号质量（判断用户是否脱下设备）
        signal_quality = "unknown"
        poor_signal = 200
        auto_disconnected = False
        
        if session['is_connected'] and session['wave_service']:
            try:
                # 获取当前脑电数据检查信号质量
                brain_data = session['wave_service'].get_brain_wave_data()
                if brain_data:
                    poor_signal = brain_data.poorSignal
                    if poor_signal < 50:
                        signal_quality = "good"
                    elif poor_signal < 100:
                        signal_quality = "fair"
                    else:
                        signal_quality = "poor"
                    
                    # 自动断开逻辑：如果信号质量持续很差，自动断开连接
                    if poor_signal >= 200:  # 完全没有信号
                        # 检查是否需要初始化poor_signal_count
                        if 'poor_signal_count' not in session:
                            session['poor_signal_count'] = 0
                        
                        session['poor_signal_count'] += 1
                        
                        # 连续5次检测到信号质量极差，自动断开
                        if session['poor_signal_count'] >= 5:
                            logger.warning(f"会话 {session_id}: 信号质量持续极差，自动断开连接")
                            
                            # 停止记录
                            if session['is_recording']:
                                session['is_recording'] = False
                                logger.info(f"会话 {session_id}: 自动停止记录")
                            
                            # 断开设备连接
                            try:
                                session['wave_service'].neuropy.stop()
                            except:
                                pass
                            
                            session['is_connected'] = False
                            session['wave_service'] = None
                            auto_disconnected = True
                            signal_quality = "disconnected"
                            
                            logger.info(f"会话 {session_id}: 设备已自动断开")
                    else:
                        # 信号质量恢复，重置计数器
                        session['poor_signal_count'] = 0
            except:
                signal_quality = "error"
        
        return JSONResponse({
            "session_id": session_id,
            "is_connected": session['is_connected'],
            "is_recording": session['is_recording'],
            "device_port": session['device_port'],
            "signal_quality": signal_quality,
            "poor_signal": poor_signal,
            "device_detected": poor_signal < 200,  # 200表示完全没有信号
            "auto_disconnected": auto_disconnected,
            "poor_signal_count": session.get('poor_signal_count', 0),
            "created_at": session['created_at'].isoformat()
        })
        
    except Exception as e:
        exception = APIException(f"获取设备状态异常: {str(e)}")
        global_exception_handler.handle_exception(exception)
        raise HTTPException(status_code=500, detail=f"获取状态失败: {str(e)}")
# 开始脑波记录
@app.post("/api/recording/start/{session_id}")
async def start_recording(session_id: str):
    """
    开始脑波记录
    
    Args:
        session_id: 会话ID
    
    Returns:
        开始记录结果
    """
    try:
        session = session_manager.get_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话不存在")
        
        if not session['is_connected']:
            raise HTTPException(status_code=400, detail="设备未连接")
        
        if session['is_recording']:
            return JSONResponse({
                "success": False,
                "message": "已在记录中",
                "session_id": session_id
            })
        
        session['is_recording'] = True
        
        return JSONResponse({
            "success": True,
            "message": "开始脑波记录",
            "session_id": session_id,
            "started_at": datetime.now().isoformat()
        })
        
    except Exception as e:
        exception = APIException(f"开始记录异常: {str(e)}")
        global_exception_handler.handle_exception(exception)
        raise HTTPException(status_code=500, detail=f"开始记录失败: {str(e)}")

@app.post("/api/recording/stop/{session_id}")
async def stop_recording(session_id: str):
    """
    停止脑波记录
    
    Args:
        session_id: 会话ID
    
    Returns:
        停止记录结果
    """
    try:
        session = session_manager.get_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话不存在")
        
        if not session['is_recording']:
            return JSONResponse({
                "success": False,
                "message": "未在记录中",
                "session_id": session_id
            })
        
        session['is_recording'] = False
        
        return JSONResponse({
            "success": True,
            "message": "停止脑波记录",
            "session_id": session_id,
            "stopped_at": datetime.now().isoformat()
        })
        
    except Exception as e:
        exception = APIException(f"停止记录异常: {str(e)}")
        global_exception_handler.handle_exception(exception)
        raise HTTPException(status_code=500, detail=f"停止记录失败: {str(e)}")

@app.put("/api/analysis/params/{session_id}")
async def update_analysis_params(session_id: str, params: AnalysisParams):
    """
    动态调整分析参数
    
    Args:
        session_id: 会话ID
        params: 新的分析参数
    
    Returns:
        更新结果
    """
    try:
        session = session_manager.get_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话不存在")
        
        # 更新分析参数
        session['analysis_params'] = params
        
        return JSONResponse({
            "success": True,
            "message": "分析参数已更新",
            "session_id": session_id,
            "params": {
                "window_size": params.window_size,
                "overlap": params.overlap,
                "bands": params.bands,
                "analysis_interval": params.analysis_interval,
                "data_buffer_size": params.data_buffer_size
            }
        })
        
    except Exception as e:
        exception = APIException(f"更新分析参数异常: {str(e)}")
        global_exception_handler.handle_exception(exception)
        raise HTTPException(status_code=500, detail=f"更新参数失败: {str(e)}")

@app.websocket("/ws/brain_state/{session_id}")
async def websocket_brain_state(websocket: WebSocket, session_id: str):
    """
    实时推送脑波分析结果的WebSocket端点
    
    Args:
        websocket: WebSocket连接
        session_id: 会话ID
    """
    await websocket.accept()
    
    # 从会话中获取 room_id
    session = session_manager.get_session(session_id)
    if not session:
        logger.error(f"WebSocket连接失败 - 会话不存在: {session_id}")
        await websocket.close(code=1008, reason="会话不存在")
        return
    
    room_id = session.get('room_id', 'default_room')
    logger.info(f"WebSocket连接建立: session_id={session_id}, room_id={room_id}")

    session_manager.websocket_connections[session_id] = websocket
    
    try:
        
        while True:
            if session['is_connected'] and session['is_recording']:
                current_time = datetime.now()
                analysis_params = session['analysis_params']
                
                # 获取当前脑电数据并添加到缓冲区
                brain_data = await get_current_brain_data_async(session)
                if brain_data:
                    # 打印波段值详细信息
                    print(f"\n=== WebSocket 波段值数据 [会话: {session_id}] ===")
                    print(f"时间戳: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
                    print(f"Delta波段: {brain_data['delta']:.4f}")
                    print(f"Theta波段: {brain_data['theta']:.4f}")
                    print(f"Alpha波段: {brain_data['alpha']:.4f}")
                    print(f"Beta波段: {brain_data['beta']:.4f}")
                    print(f"Gamma波段: {brain_data['gamma']:.4f}")
                    print(f"信号质量: {brain_data['poor_signal']}")
                    print(f"注意力: {brain_data['attention']}")
                    print(f"冥想度: {brain_data['meditation']}")
                    print("=" * 50)
                    
                    session['data_buffer'].append({
                        'timestamp': current_time,
                        'data': brain_data
                    })
                    
                    # 保持缓冲区大小
                    if len(session['data_buffer']) > analysis_params.data_buffer_size:
                        session['data_buffer'].pop(0)
                
                # 检查是否需要进行脑状态分析
                should_analyze = False
                if session['last_analysis_time'] is None:
                    should_analyze = True
                else:
                    time_diff = (current_time - session['last_analysis_time']).total_seconds()
                    if time_diff >= analysis_params.analysis_interval:
                        should_analyze = True
                
                if should_analyze and len(session['data_buffer']) >= analysis_params.analysis_interval:
                    # 进行脑状态分析
                    brain_state = await get_brain_state_async(session)
                    
                    if brain_state:
                        # 打印用户状态分析结果
                        print(f"\n*** 用户状态分析结果 [会话: {session_id}] ***")
                        print(f"分析时间: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
                        print(f"用户状态: {brain_state.state}")
                        print(f"置信度: {brain_state.confidence:.4f}")
                        print(f"分析详情: {brain_state.details}")
                        print(f"使用数据点数: {len(session['data_buffer'])}")
                        print(f"分析间隔: {analysis_params.analysis_interval}秒")
                        print("*" * 50)
                        
                        await websocket.send_json({
                            "session_id": session_id,
                            "room_id": room_id,
                            "timestamp": current_time.isoformat(),
                            "analysis_interval": analysis_params.analysis_interval,
                            "data_points_used": len(session['data_buffer']),
                            "brain_state": {
                                "state": brain_state.state,
                                "confidence": brain_state.confidence,
                                "details": brain_state.details
                            }
                        })
                        
                        # 保存最新结果和分析时间
                        session['last_result'] = brain_state
                        session['last_analysis_time'] = current_time
            
            # 等待1秒后继续
            await asyncio.sleep(1)
            
    except WebSocketDisconnect:
        logger.info(f"WebSocket连接断开: {session_id}")
        if session_id in session_manager.websocket_connections:
            del session_manager.websocket_connections[session_id]
    except Exception as e:
        websocket_error = APIException(
            f"WebSocket连接异常: {e}",
            endpoint="websocket_brain_state"
        )
        global_exception_handler.handle_exception(websocket_error)
        await websocket.send_json({
            "error": f"WebSocket异常: {str(e)}",
            "session_id": session_id
        })


@app.websocket("/ws/progressive_data/{session_id}")
async def websocket_progressive_data(websocket: WebSocket, session_id: str):
    """
    渐进式数据推送WebSocket端点
    每秒返回Delta/Theta数据，5秒预热后开始脑状态分析
    
    Args:
        websocket: WebSocket连接
        session_id: 会话ID
    """
    await websocket.accept()
    
    # 从会话中获取 room_id
    session = session_manager.get_session(session_id)
    if not session:
        logger.error(f"渐进式WebSocket连接失败 - 会话不存在: {session_id}")
        await websocket.close(code=1008, reason="会话不存在")
        return
    
    room_id = session.get('room_id', 'default_room')
    logger.info(f"渐进式WebSocket连接建立: session_id={session_id}, room_id={room_id}")
    
    session_manager.websocket_connections[f"{session_id}_progressive"] = websocket
    
    try:
        
        progressive_manager = session['progressive_manager']
        
        while True:
            if session['is_connected'] and session['is_recording']:
                current_time = datetime.now()
                
                # 获取当前脑电数据
                brain_data = await get_current_brain_data_async(session)
                if brain_data:
                    # 添加数据到渐进式管理器
                    progressive_manager.add_data_point(brain_data)
                    
                    # 获取预热进度
                    warmup_progress = progressive_manager.get_warmup_progress()
                    
                    # 获取最新的波段数据
                    latest_wave_data = progressive_manager.get_latest_wave_data()
                    
                    # 获取连接状态信息
                    connection_status = progressive_manager.get_connection_status()
                    
                    # 构建基础响应数据
                    response_data = {
                        "session_id": session_id,
                        "room_id": room_id,
                        "timestamp": current_time.isoformat(),
                        "warmup_progress": warmup_progress,
                        "wave_data": latest_wave_data,
                        "connection_status": connection_status
                    }
                    
                    # 检查是否需要自动断开
                    if connection_status.get("should_auto_disconnect", False):
                        logger.warning(f"检测到信号质量持续较差，建议断开会话: session_id={session_id}, room_id={room_id}")
                        response_data["auto_disconnect_warning"] = {
                            "message": "检测到设备可能未正确佩戴，建议重新调整设备位置或断开连接",
                            "action": "auto_disconnect_suggested"
                        }
                    
                    # 如果预热完成，尝试进行脑状态分析
                    if progressive_manager.can_analyze_brain_state():
                        analysis_data = progressive_manager.get_analysis_data()
                        if analysis_data:
                            # 使用现有的脑状态服务进行分析
                            brain_state_service = session['brain_state_service']
                            if brain_state_service:
                                try:
                                    brain_state = await asyncio.get_event_loop().run_in_executor(
                                        session_manager.executor,
                                        brain_state_service.classify_brain_state,
                                        analysis_data
                                    )
                                    
                                    if brain_state:
                                        response_data["brain_state"] = {
                                            "state": brain_state.state,
                                            "confidence": brain_state.confidence,
                                            "details": brain_state.details
                                        }
                                        
                                        # 打印渐进式分析结果
                                        print(f"\n*** 渐进式用户状态分析 [会话: {session_id}] ***")
                                        print(f"分析时间: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
                                        print(f"用户状态: {brain_state.state}")
                                        print(f"置信度: {brain_state.confidence:.4f}")
                                        print(f"预热状态: {warmup_progress['status']}")
                                        print(f"预热进度: {warmup_progress['percentage']:.1f}%")
                                        print("*" * 50)
                                        
                                except Exception as e:
                                    logger.error(f"脑状态分析异常: {e}")
                                    response_data["analysis_error"] = str(e)
                    
                    # 发送响应数据
                    await websocket.send_json(response_data)
                    
                    # 打印波段数据（仅在预热期间）
                    if warmup_progress['status'] == 'warming_up' and latest_wave_data:
                        print(f"\n=== 渐进式波段数据 [会话: {session_id}] ===")
                        print(f"时间戳: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
                        print(f"Delta: {latest_wave_data['delta']:.4f}")
                        print(f"Theta: {latest_wave_data['theta']:.4f}")
                        print(f"预热进度: {warmup_progress['percentage']:.1f}%")
                        print(f"剩余时间: {warmup_progress['remaining_seconds']:.1f}秒")
                        print("=" * 45)
            
            # 等待1秒后继续
            await asyncio.sleep(1)
            
    except WebSocketDisconnect:
        logger.info(f"渐进式WebSocket连接断开: {session_id}")
        if f"{session_id}_progressive" in session_manager.websocket_connections:
            del session_manager.websocket_connections[f"{session_id}_progressive"]
    except Exception as e:
        websocket_error = APIException(
            f"渐进式WebSocket连接异常: {e}",
            endpoint="websocket_progressive_data"
        )
        global_exception_handler.handle_exception(websocket_error)
        await websocket.send_json({
            "error": f"渐进式WebSocket异常: {str(e)}",
            "session_id": session_id
        })


async def get_current_brain_data_async(session: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    异步获取当前脑电数据
    
    Args:
        session: 会话信息
    
    Returns:
        当前脑电数据
    """
    try:
        if not session['wave_service']:
            return None
        
        def get_brain_data_sync():
            try:
                brain_data = session['wave_service'].get_brain_wave_data()
                if not brain_data:
                    return None
                
                total_power = brain_data.delta + brain_data.theta + brain_data.alpha + brain_data.beta + brain_data.gamma
                if total_power == 0:
                    return None
                
                result = {
                    'delta': brain_data.delta / total_power,
                    'theta': brain_data.theta / total_power,
                    'alpha': brain_data.alpha / total_power,
                    'beta': brain_data.beta / total_power,
                    'gamma': brain_data.gamma / total_power,
                    'poor_signal': brain_data.poorSignal,
                    'attention': brain_data.attention,
                    'meditation': brain_data.meditation
                }
                
                # 打印原始数据和归一化后的数据
                print(time.time())
                print(f"\n--- 原始脑电数据 ---")
                print(f"Delta原始值: {brain_data.delta}, 归一化: {result['delta']:.4f}")
                print(f"Theta原始值: {brain_data.theta}, 归一化: {result['theta']:.4f}")
                print(f"Alpha原始值: {brain_data.alpha}, 归一化: {result['alpha']:.4f}")
                print(f"Beta原始值: {brain_data.beta}, 归一化: {result['beta']:.4f}")
                print(f"Gamma原始值: {brain_data.gamma}, 归一化: {result['gamma']:.4f}")
                print(f"总功率: {total_power}")
                print("-------------------")
                
                return result
            except Exception as e:
                data_error = DeviceConnectionException(
                    f"获取脑电数据失败: {e}",
                    device_type="brain_wave_data_retrieval"
                )
                global_exception_handler.handle_exception(data_error)
                return None
        
        loop = asyncio.get_event_loop()
        result = await loop.run_in_executor(session_manager.executor, get_brain_data_sync)
        return result
        
    except Exception as e:
        async_data_error = APIException(
            f"异步获取脑电数据异常: {e}",
            endpoint="get_current_brain_data_async"
        )
        global_exception_handler.handle_exception(async_data_error)
        return None

async def get_brain_state_async(session: Dict[str, Any]) -> Optional[BrainStateOutput]:
    """
    异步获取脑状态分析结果（基于缓冲区数据）
    
    Args:
        session: 会话信息
    
    Returns:
        脑状态输出结果
    """
    try:
        if not session['brain_state_service'] or not session['data_buffer']:
            return None
        
        def get_brain_state_sync():
            try:
                # 从缓冲区获取数据
                buffer_data = session['data_buffer']
                if len(buffer_data) == 0:
                    return None
                
                # 构建BrainWaveRatesInput
                from models.brain_state_models import BrainWaveRatesInput
                
                # 提取各频段数据
                delta_rates = [item['data']['delta'] for item in buffer_data if item['data']]
                theta_rates = [item['data']['theta'] for item in buffer_data if item['data']]
                alpha_rates = [item['data']['alpha'] for item in buffer_data if item['data']]
                beta_rates = [item['data']['beta'] for item in buffer_data if item['data']]
                gamma_rates = [item['data']['gamma'] for item in buffer_data if item['data']]
                
                if not delta_rates:  # 如果没有有效数据
                    return None
                
                # 创建输入数据
                start_time = buffer_data[0]['timestamp'].isoformat()
                end_time = buffer_data[-1]['timestamp'].isoformat()
                
                rates_input = BrainWaveRatesInput(
                    session_id=session['id'],
                    start_time=start_time,
                    end_time=end_time,
                    relative_rates={
                        'delta': delta_rates,
                        'theta': theta_rates,
                        'alpha': alpha_rates,
                        'beta': beta_rates,
                        'gamma': gamma_rates
                    }
                )
                
                # 使用BrainStateService进行分析
                result = session['brain_state_service'].classify_brain_state(rates_input)
                return result
                
            except Exception as e:
                state_error = APIException(
                    f"获取脑状态失败: {e}",
                    endpoint="get_brain_state_sync"
                )
                global_exception_handler.handle_exception(state_error)
                return None
        
        # 在线程池中执行
        loop = asyncio.get_event_loop()
        result = await loop.run_in_executor(session_manager.executor, get_brain_state_sync)
        return result
        
    except Exception as e:
        async_error = APIException(
            f"异步获取脑状态异常: {e}",
            endpoint="get_brain_state_async"
        )
        global_exception_handler.handle_exception(async_error)
        return None

@app.get("/api/sessions")
async def list_sessions():
    """
    获取所有会话列表
    
    Returns:
        会话列表
    """
    sessions = []
    for session_id, session in session_manager.sessions.items():
        sessions.append({
            "session_id": session_id,
            "created_at": session['created_at'].isoformat(),
            "is_connected": session['is_connected'],
            "is_recording": session['is_recording'],
            "device_port": session['device_port'],
            "room_id": session.get('room_id', 'default_room')
        })
    
    return JSONResponse({
        "sessions": sessions,
        "total": len(sessions)
    })

@app.delete("/api/sessions/{session_id}")
async def delete_session(session_id: str):
    """
    删除会话
    
    Args:
        session_id: 会话ID
    
    Returns:
        删除结果
    """
    try:
        session = session_manager.get_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话不存在")
        
        session_manager.remove_session(session_id)
        
        return JSONResponse({
            "success": True,
            "message": "会话已删除",
            "session_id": session_id
        })
        
    except Exception as e:
        exception = APIException(f"删除会话异常: {str(e)}")
        global_exception_handler.handle_exception(exception)
        raise HTTPException(status_code=500, detail=f"删除会话失败: {str(e)}")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)